﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace Win.CSkin.Test
{
    public partial class Form2 : Form
    {
        List<TestUserInfo> list = new List<TestUserInfo>();
        private static List<string> strList = new List<string>();
        List<DPS_StorageCheckInfo> testlist = new List<DPS_StorageCheckInfo>();

        //Task取消
        CancellationTokenSource cts1 = new CancellationTokenSource();
        //Task取消
        CancellationTokenSource cts2 = new CancellationTokenSource();

        //WCF同步内容格式
        private const string DSP_CONSIS =
            "<ROOT>" +
            "<OPSYSTEM>HIS</OPSYSTEM>" +    //系统名称
            "<OPWINID>X</OPWINID>" +
            "<OPTYPE>M2252</OPTYPE>" +
            "<OPIP>{0}</OPIP>" +             //操作主机IP
            "<OPMANNO>{1}</OPMANNO>" +       //员工号
            "<OPMANNAME>{2}</OPMANNAME>" +   //员工名称
            "<CONSIS_ORDER_MSTVW>" +
            " <ADVICE_CODE>{3}</ADVICE_CODE>" +  //瓶签号
            " <ALLOWIND>{4}</ALLOWIND>" +          //Y摆药/N取消
            "</CONSIS_ORDER_MSTVW>" +
            "</ROOT>";

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            var ssss = list.Any();
            list = list.OrderBy(t => t.UserId).ToList();

            this.BeginInvoke((Action)(() =>
            {
                //MessageBox.Show("BeginInvoke");
            }));

            for (int i = 0; i < 10; i++) //插入10条数据。
            {
                TestUserInfo user = new TestUserInfo
                {
                    UserId = "UserId" + i,
                    UserName = "UserName" + i,
                    UserEnabled = i % 2 == 0
                };
                list.Add(user);
            }

            //foreach (var info in list)
            //{
            //    if (info.UserId == "UserId1")
            //    {
            //        list.Remove(info);
            //    }
            //}

            for (int i = 0; i < list.Count;)
            {
                if (list.Count > 7)
                {
                    list.RemoveAt(i);
                    continue;
                }

                i++;
            }

            TestUserInfo tu = list.FirstOrDefault();

            if (list.Count > 4)
            {
                list.RemoveRange(0, list.Count - 4);
            }

            list.Remove(tu);
            var ttt = tu;

            for (int i = 1; i <= 10; i++)
            {
                DPS_StorageCheckInfo info = new DPS_StorageCheckInfo
                {
                    Storage_CheckNum = i
                };
                CommonObject.DPS_Current_StorageChecks.Add(info);
            }

            for (int i = 1; i <= 10; i++)
            {
                DPS_StorageCheckInfo info = new DPS_StorageCheckInfo
                {
                    Storage_CheckNum = i
                };
                CommonObject.DPS_Current_StorageCheckBags.Add(info);
            }

            #region tableLayoutPanel

            //首行序号列
            for (var i = 1; i < 3; ++i)
            {
                var label = new Label();
                label.Dock = DockStyle.Fill;
                label.Font = new System.Drawing.Font("宋体", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                label.TextAlign = ContentAlignment.MiddleCenter;
                label.Text = (i).ToString();
                tableLayoutPanel1.Controls.Add(label, i, 0);
            }
            //首列行序号
            for (var i = 1; i < 3; ++i)
            {
                var seqCheck = new CheckBox();
                seqCheck.Dock = DockStyle.Fill;
                seqCheck.Text = (tableLayoutPanel1.RowCount - i + 10).ToString();
                seqCheck.TextAlign = ContentAlignment.MiddleLeft;
                tableLayoutPanel1.Controls.Add(seqCheck, 0, i);
                //var label = new Label();
                //label.Dock = DockStyle.Fill;
                //var font = new System.Drawing.Font("宋体", 15.75F, System.Drawing.FontStyle.Bold | FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                //label.Font = font;
                //label.TextAlign = ContentAlignment.MiddleCenter;
                //label.Text = (3 - i).ToString();
                //tableLayoutPanel1.Controls.Add(label, 0, i);
            }
            for (var row = 1; row < 3; ++row)
            {
                for (var col = 1; col < 3; ++col)
                {
                    var panel = new TableLayoutPanel();
                    panel.Controls.Clear();
                    panel.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
                    panel.RowCount = 1;
                    panel.ColumnCount = 8;
                    float colwidth = 100f / 8; // panel.Width * 0.2f; //每列宽度
                    //panel.Click += MedicinePanel_Click;
                    //panel.Tag = null;
                    panel.BackColor = Color.WhiteSmoke;
                    panel.Cursor = System.Windows.Forms.Cursors.Default;

                    for (int i = 0; i < 8; i++)
                    {
                        panel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, colwidth));

                        var childLabel = new Label();
                        childLabel.BackColor = Color.Green;
                        childLabel.Click += PanelClick;
                        childLabel.Tag = $"row{row} col{col} child{i}";
                        childLabel.Text = (i + 1).ToString();
                        childLabel.TextAlign = ContentAlignment.MiddleCenter;
                        panel.Controls.Add(childLabel, i, 0);
                    }

                    tableLayoutPanel1.Controls.Add(panel, col, row);
                }
            }

            #endregion

            label1.Tag = 3;

            cts1.Token.Register(() =>
            {
                this.Invoke((Action)(() =>
                {
                    richTextBox1.Text += " Task1取消 ";
                }));
            });
            cts2.Token.Register(() =>
            {
                this.Invoke((Action)(() =>
                {
                    richTextBox1.Text += " Task2取消 ";
                }));
            });
        }

        private void PanelClick(object sender, EventArgs e)
        {
            var panel = sender as Label;
            MessageBox.Show(panel.Tag.ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var user = list.FirstOrDefault(t => t.UserId == "UserId1");
            user.UserName = "Test";

            MessageBox.Show(list.FirstOrDefault(t => t.UserId == "UserId1").UserName);

            DPS_IssueData_LabelInfo labelInfo = new DPS_IssueData_LabelInfo();

            DPS_IssueData_LabelDetailInfo detailInfo = new DPS_IssueData_LabelDetailInfo
            {
                IssueData_DrugNum = 10,
                IssueData_DrugNum_Print = 10
            };
            labelInfo.IssueData_DrugsInfo.Add(detailInfo);
            labelInfo.IssueData_DrugsInfo_Print.Add(detailInfo);

            var drugItem = labelInfo.IssueData_DrugsInfo.FirstOrDefault();
            drugItem.IssueData_DrugNum = 4;

            var item = labelInfo.IssueData_DrugsInfo_Print.FirstOrDefault();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DPS_StorageCheckInfo info = new DPS_StorageCheckInfo
            {
                Storage_CheckNum = new Random().Next(11, 100)
            };
            CommonObject.DPS_Current_StorageChecks.Add(info);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            CommonObject.DPS_Current_StorageChecks.Clear();

            var item = CommonObject.DPS_Current_StorageChecks.FirstOrDefault(t => t.Storage_BoxID == "0000000");

            //CommonObject.DPS_Current_StorageChecks = null;

            CommonObject.DPS_Current_StorageChecks.RemoveAll(t => t.Storage_BoxID == "0000000");

            CommonObject.DPS_Current_StorageChecks.RemoveAll(t => t.Storage_BoxID == "00000001");

            item = CommonObject.DPS_Current_StorageChecks.FirstOrDefault(t => t.Storage_BoxID == "0000000");
            CommonObject.DPS_Current_StorageChecks.RemoveAll(t => t.Storage_BoxID == "0000000");

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var list = CommonObject.DPS_Current_StorageChecks;

                    string str = string.Empty;
                    list.ForEach(t =>
                    {
                        //if (t.Storage_CheckNum == 2) return;

                        str += t.Storage_CheckNum.ToString() + "-";
                    });

                    richTextBox1.Text = "count:" + list.Count + " items:" + str;
                    Thread.Sleep(1000);
                }
            });

        }

        private void button17_Click(object sender, EventArgs e)
        {
            //var list = CommonObject.DPS_Current_StorageChecks;
            //List<DPS_StorageCheckInfo> testlist = new List<DPS_StorageCheckInfo>();

            testlist = new List<DPS_StorageCheckInfo>(CommonObject.DPS_Current_StorageChecks);
            //var count = list.Count;
            var count = testlist.Count;
            //CommonObject.DPS_Current_StorageChecks.RemoveAt(0);
            //count = list.Count;
            count = testlist.Count;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 5; i++)
            {
                richTextBox1.Text += i.ToString();
                var task1 = Task.Factory.StartNew(() =>
                  {
                      this.BeginInvoke((Action)(() =>
                      {
                          richTextBox1.Text += " task1";
                      }));
                      Thread.Sleep(2000);
                  });

                var task2 = task1.ContinueWith(task =>
                {
                    this.BeginInvoke((Action)(() =>
                    {
                        richTextBox1.Text += " task2";
                    }));
                    Thread.Sleep(4000);
                });
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var count = 0;

            //测试Exception
            ////任务一
            //System.Threading.Timer timer1 = new System.Threading.Timer((obj) =>
            //{
            //    var str = "a" + ++count;
            //    strList.Add(str);
            //    Console.WriteLine("添加了：" + str);
            //}, null, 0, 1000);

            ////任务二
            //System.Threading.Timer timer2 = new System.Threading.Timer((obj) =>
            //{
            //    var aa = strList.FirstOrDefault(t => t == "a3");
            //    strList.RemoveAll(t => t == "a3");
            //    foreach (var item in strList)
            //    {
            //        Console.WriteLine("显示：" + item);
            //    }
            //}, null, 0, 1000);

            //var cc = CommonObject.DPS_Current_StorageCheckBags.FirstOrDefault(t => t.Storage_CheckNum == 3);
            //cc.Storage_CheckNum = 30;
            //var order = CommonObject.DPS_Current_StorageCheckBags.OrderBy(t => t.Storage_CheckNum);

            //foreach (var checkInfo in CommonObject.DPS_Current_StorageCheckBags)
            ////foreach (var checkInfo in order)
            //{
            //    //无法指定删除某一项，ConcurrentBag以队列的方式先进先出
            //    //if (checkInfo.Storage_CheckNum == 3)
            //    //{
            //    DPS_StorageCheckInfo take;
            //    CommonObject.DPS_Current_StorageCheckBags.TryTake(out take);
            //    richTextBox1.Text = take.Storage_CheckNum.ToString();
            //    //}
            //}

            //var list = CommonObject.DPS_Current_StorageCheckBags;


            ConcurrentQueue<DPS_StorageCheckInfo> dict = new ConcurrentQueue<DPS_StorageCheckInfo>();
            dict.Enqueue(new DPS_StorageCheckInfo { Storage_Lay = 1 }); dict.Enqueue(new DPS_StorageCheckInfo { Storage_Lay = 2 }); dict.Enqueue(new DPS_StorageCheckInfo { Storage_Lay = 3 });

            var bl = dict.Any(t => t.Storage_Lay == 2);
            bl = dict.Any(t => t.Storage_Lay == 4);

            byte[] result = new byte[1525305345];
            ConcurrentDictionary<string, TestUserInfo> retDict = new ConcurrentDictionary<string, TestUserInfo>();
            retDict.GetOrAdd("a1", new TestUserInfo { UserEnabled = true, UserId = "1", Bytes = new byte[] { 1, 3 } });
            retDict.GetOrAdd("a2", new TestUserInfo { UserEnabled = true, UserId = "2", Bytes = new byte[] { 2 } });
            retDict.GetOrAdd("a3", new TestUserInfo { UserEnabled = true, UserId = "3", Bytes = new byte[] { 3 } });
            retDict.AddOrUpdate("a3", new TestUserInfo { }, (key, value) => new TestUserInfo { });
            retDict.AddOrUpdate("a4", new TestUserInfo { UserEnabled = true, UserId = "4", Bytes = new byte[] { 4 } }, (key, value) => new TestUserInfo { UserEnabled = true, UserId = "4", Bytes = new byte[] { 4 } });
            retDict.TryGetValue("a1", out TestUserInfo dbyte);
            dbyte.UserId = "aa";
            retDict.TryRemove("a2", out TestUserInfo rr);
            retDict.TryUpdate("a1", new TestUserInfo { UserEnabled = true, UserId = "a1", Bytes = new byte[] { 11 } }, dbyte);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //int count = 0;
            //while (count < 2)
            //{
            //    count++;

            //    if (count == 2)
            //    {
            //        MessageBox.Show("2");
            //    }
            //}

            bool opened = false;
            DateTime startTime = DateTime.Now;
            while (startTime.AddSeconds(15).CompareTo(DateTime.Now) > 0 && opened == false)
            {
                //由于打印队列有打开打印机端口的可能性，
                //重复打印机最多打开15秒
                System.Threading.Thread.Sleep(100);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            int[] arr = new int[] { };
            arr = new int[4] { 1, 2, 3, 4 };

            byte[] pbyRecv = new byte[4];
            pbyRecv[2] = 0x10;
            var r1 = pbyRecv[2] & 0xF0;
            var r2 = pbyRecv[2] & 0x0F;

            //MessageBox.Show(pbySendData.Count().ToString());

            Int32 code = 1000000000; //10进制转为二进制
            //Int16 code = 10;
            var bytes = BitConverter.GetBytes(code);
            BitArray bitArray = new BitArray(bytes);

            float ff = 2;
            bytes = BitConverter.GetBytes(ff);
            bytes = BitConverter.GetBytes(2.0f);
            ff = 0;
            ff = BitConverter.ToSingle(bytes, 0);

            string bitStr = Convert.ToString(code, 2);
        }

        private void Label1_MouseHover(object sender, EventArgs e)
        {
            var label = sender as Label;
            ToolTip tip = new ToolTip();
            tip.IsBalloon = true;
            label.Tag = 4;
            tip.SetToolTip(label, label.Tag.ToString());
        }

        private void button8_Click(object sender, EventArgs e)
        {
            SortedList<int, string> lstBarCode = new SortedList<int, string>();
            lstBarCode.Add(1, "101");
            lstBarCode.Add(2, "201");
            lstBarCode.Add(3, "301");

            var list = lstBarCode.ToList();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var json = jss.Serialize(list);
            richTextBox1.Text = json;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            //添加测试数据
            for (int i = 1; i <= 3; i++)
            {
                DPS_LayCheckInfo layCheckInfo = new DPS_LayCheckInfo
                {
                    Check_Lay = i
                };
                CommonObject.DPS_Current_StorageChecksNew.Add(layCheckInfo);
            }

            //处理队列更新页面状态、更新DB、更新PLC
            Task.Factory.StartNew(() =>
            {
                try
                {
                    while (true)
                    {
                        if (cts2.Token.IsCancellationRequested)
                        {
                            this.Invoke((Action)(() =>
                            {
                                richTextBox1.Text += " task2 IsCancellationRequested";
                            }));
                        }
                        cts2.Token.ThrowIfCancellationRequested();

                        var list = CommonObject.DPS_Current_StorageChecksNew;
                        if (!list.Any())
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                        //所有层都已盘点并更新完成
                        if (list.Count == list.FindAll(t => t.IsLayChecked).Count)
                        {
                            this.BeginInvoke((Action)(() =>
                                {
                                    lblCheckOK.BackColor = Color.Green;
                                }));
                            break; //退出循环
                        }

                        //未更新数据的层
                        var unDealLays = list.FindAll(t => !t.IsLayChecked).OrderBy(t => t.Check_Lay).ToList();
                        //遍历层
                        unDealLays.ForEach(layInfo =>
                       {
                           if (cts2.Token.IsCancellationRequested)
                           {
                               this.Invoke((Action)(() =>
                               {
                                   richTextBox1.Text += " task2 IsCancellationRequested";
                               }));
                           }
                           cts2.Token.ThrowIfCancellationRequested();

                           //无单元格盘点数据
                           if (layInfo.UnitCheckInfos == null || !layInfo.UnitCheckInfos.Any())
                           {
                               //layInfo.IsLayChecked = true;
                               //Thread.Sleep(1000);
                               return;
                           }

                           //盘点正常的单元格
                           var normalCheckUnits = layInfo.UnitCheckInfos.FindAll(t => t.Storage_CheckStatus == 0);
                           //盘点正常且DB、PLC都更新成功
                           var doneCheckUnits = layInfo.UnitCheckInfos.FindAll(t => t.Storage_CheckStatus == 0 && t.DB_Update_Status && t.PLC_Update_Status);
                           //当前层盘点正常的DB、PLC都更新成功即当前层盘点完成
                           if (normalCheckUnits.Count == doneCheckUnits.Count)
                           {
                               layInfo.IsLayChecked = true;
                               this.BeginInvoke((Action)(() =>
                               {
                                   if (layInfo.Check_Lay == 1)
                                   {
                                       lbllay1.BackColor = Color.Green;
                                   }
                                   else if (layInfo.Check_Lay == 2)
                                   {
                                       lbllay2.BackColor = Color.Green;
                                   }
                                   else if (layInfo.Check_Lay == 3)
                                   {
                                       lbllay3.BackColor = Color.Green;
                                   }
                                   //Application.DoEvents();
                               }));
                           }
                           else
                           {
                               //layInfo.IsLayChecked = false;
                               this.Invoke((Action)(() =>
                                {
                                    if (layInfo.Check_Lay == 1)
                                    {
                                        lbllay1.BackColor = Color.Red;
                                    }
                                    else if (layInfo.Check_Lay == 2)
                                    {
                                        lbllay2.BackColor = Color.Red;
                                    }
                                    else if (layInfo.Check_Lay == 3)
                                    {
                                        lbllay3.BackColor = Color.Red;
                                    }
                                    //Application.DoEvents();
                                }));
                           }
                       });
                    }
                }
                catch (OperationCanceledException ocex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task2 OperationCanceledException " + ocex.Message;
                    }));
                }
                catch (ObjectDisposedException odex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task2 ObjectDisposedException " + odex.Message;
                    }));
                }
                catch (Exception ex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task2 Exception " + ex.Message;
                    }));
                }
            }, cts2.Token);

        }

        private void button10_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //遍历层盘点
                    CommonObject.DPS_Current_StorageChecksNew.OrderBy(t => t.Check_Lay).ToList().ForEach(layInfo =>
                     {
                         layInfo.UnitCheckInfos = new List<DPS_StorageCheckInfo>();
                         //临时存放单元格盘点信息，等整层的单元格都盘点完统一加入队列处理
                         var unitCheckInfos = new List<DPS_StorageCheckInfo>();
                         for (int i = 1; i < 6; i++)
                         {
                             if (cts1.Token.IsCancellationRequested)
                             {
                                 this.Invoke((Action)(() =>
                                 {
                                     richTextBox1.Text += " task1 IsCancellationRequested";
                                 }));
                             }
                             cts1.Token.ThrowIfCancellationRequested();

                             DPS_StorageCheckInfo checkInfo = new DPS_StorageCheckInfo
                             {
                                 Storage_Lay = layInfo.Check_Lay,
                                 Storage_Column = 1,
                                 Storage_BoxID = "101",
                                 Storage_UnitID = i,
                                 Storage_DrugID = "1001",
                                 Storage_Drug_Diameter = 1000,
                                 Storage_CheckNum = i,
                                 Storage_CheckStatus = 0,
                                 DB_Update_Status = true,
                                 PLC_Update_Status = true // i / 2 == 1
                             };
                             //加入更新队列统一更新DB、PLC
                             unitCheckInfos.Add(checkInfo);
                         }

                         // 加入队列更新数据库、PLC
                         layInfo.UnitCheckInfos = unitCheckInfos;

                         Thread.Sleep(5000);
                     });
                }
                catch (OperationCanceledException ocex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task1 OperationCanceledException " + ocex.Message;
                    }));
                }
                catch (ObjectDisposedException odex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task1 ObjectDisposedException " + odex.Message;
                    }));
                }
                catch (Exception ex)
                {
                    this.Invoke((Action)(() =>
                    {
                        richTextBox1.Text += " task1 Exception " + ex.Message;
                    }));
                }

            }, cts1.Token);
        }

        /// <summary>
        /// 取消盘点线程
        /// </summary>
        private void button18_Click(object sender, EventArgs e)
        {
            cts1.Cancel();
            cts2.Cancel();
        }

        //关闭线程
        private void button12_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Text = "关闭中...";
                Application.DoEvents();

                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(5000);
                    CommonObject.DPS_Current_StorageChecks.RemoveRange(0, 10);
                    for (int i = 1; i <= 10; i++)
                    {
                        CommonObject.DPS_Current_StorageChecks.RemoveAll(t => t.Storage_CheckNum == i);
                    }
                });

                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);

                        if (!CommonObject.DPS_Current_StorageChecks.Any())
                        {
                            this.BeginInvoke((Action)(() =>
                            {
                                richTextBox1.Text = "已清空";
                                Application.DoEvents();
                            }));

                            break;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void btnToUnicode_Click(object sender, EventArgs e)
        {
            string code = Utils.StringToUnicode(txtUnicode.Text);
            code = code.Trim();

            richTextBox1.Text = code;
        }

        private void btnDeUnicode_Click(object sender, EventArgs e)
        {
            string code = Utils.DeUnicode(txtUnicode.Text);
            code = code.Trim();

            richTextBox1.Text = code;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            string str = @"对路径“E:\李丹丹\Rbo\RLPdm\RLPdm\Upload\DrawingZhi\17509.15-4.pdf”的访问被拒绝。";

            str = GetString(str);
            richTextBox1.Text = str;
        }

        /// <summary>
        /// 去除JSON转义特殊字符
        /// </summary>
        /// <param name="theString"></param>
        /// <returns></returns>
        private string GetString(string theString)
        {
            theString = theString.Replace(">", "&gt;");
            theString = theString.Replace("<", "&lt;");
            theString = theString.Replace(" ", "&nbsp;");
            theString = theString.Replace("\"", "&quot;");
            theString = theString.Replace("\'", "&#39;");
            theString = theString.Replace("\\", "\\\\");//对斜线的转义  
            theString = theString.Replace("\n", "\\n");  //注意php中替换的时候只能用双引号"\n"
            theString = theString.Replace("\r", "\\r");

            return theString;
        }

        private void btnYesNo_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否关闭", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question).GetHashCode() == 7) //选No
            {
                return;
            }

            Close();
        }

        /// <summary>
        /// 等待窗口
        /// </summary>
        private void btnWaiting_Click(object sender, EventArgs e)
        {
            frmWaitingBox waiting = new frmWaitingBox("");
            //waiting.Desc = "加载中...";
            waiting.Show(this);
            Application.DoEvents();

            Thread.Sleep(4000);
            waiting.waiting = false;
        }

        //海茨WCF8000回传接口测试
        private void button13_Click(object sender, EventArgs e)
        {
            //20190529102649
            string labelNo = lblLabelNo.Text.Trim();
            string param = string.Format(DSP_CONSIS, Utils.getIP(), "81419", "金唐慧", labelNo, "Y");

            ServiceHisConsis.HisServiceClient service = new ServiceHisConsis.HisServiceClient();

            string result = service.HisTransData(param);
            richTextBox1.Text = result;
        }

        private void button14_Click(object sender, EventArgs e)
        {
            //获取单元格中心坐标
            int cellposX = Convert.ToInt32(txtCenterX.Text);
            //药品直径
            double diameter = Convert.ToDouble(txtDrugDiameter.Text);
            //直径有效区间
            double validRange = Convert.ToDouble(txtValidRange.Text);
            // 激光位移速度0.01mm/s
            double LaserMeasureSpeed = 6000;
            //激光扫描周期(ms)
            int LaserMeasureDataCycle = 2;
            //起始点坐标索引
            int validDataStartIndex = Convert.ToInt32(txtStartIndex.Text);

            //盘点点坐标左右偏移量（按照设定好的比例）
            int drugCheckOffset_X = (int)(diameter * validRange);
            //盘点点坐标左偏移点坐标索引
            int dataIndexFrom = (int)((double)(cellposX - drugCheckOffset_X) / LaserMeasureSpeed * 1000.0) / LaserMeasureDataCycle + validDataStartIndex;
            //盘点点坐标右偏移点坐标索引
            int dataIndexTo = (int)((double)(cellposX + drugCheckOffset_X) / LaserMeasureSpeed * 1000.0) / LaserMeasureDataCycle + validDataStartIndex;

            txtValidIndexFrom.Text = dataIndexFrom.ToString();
            txtValidIndexTo.Text = dataIndexTo.ToString();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            //激光到药盒前端距离 14960
            int LaserMeasureToCassetteFront = Convert.ToInt32(txtBoxFront.Text);
            //药盒深度
            int boxDepth = Convert.ToInt32(txtBoxDepth.Text);
            //药品直径
            double diameter = Convert.ToDouble(txtDrugDiameter.Text);

            #region 计算数量
            if (!string.IsNullOrWhiteSpace(txtCheckData.Text))
            {
                //激光测量值（测量有效区间内的最大值）
                int checkData = Convert.ToInt32(txtCheckData.Text);
                //盘点深度：盘点药品的坐标距离药盒最前端的距离差
                int stockDepth = LaserMeasureToCassetteFront - checkData;
                //（药盒深度-盘点深度）/药品直径=药品库存(向下取整)
                double stockNum = Math.Round((boxDepth - stockDepth) / diameter, 2);
                txtPDNum.Text = stockNum.ToString();
                return;
            }
            #endregion

            #region 计算测量值
            if (!string.IsNullOrWhiteSpace(txtPDNum.Text))
            {
                int num = Convert.ToInt32(txtPDNum.Text);
                //盘点深度
                double stockDepth = (double)boxDepth - num * diameter;
                //激光测量值
                double checkData = LaserMeasureToCassetteFront - stockDepth;

                txtCheckData.Text = checkData.ToString();
                return;
            }
            #endregion

        }

        private void button16_Click(object sender, EventArgs e)
        {
            string str = txtBytes.Text;

            byte[] bytes = Encoding.ASCII.GetBytes(str);
            short[] arr = new short[bytes.Length / 2];
            Buffer.BlockCopy((Array)bytes, 0, (Array)arr, 0, arr.Length * 2);

            //BitArray bitArray = new BitArray(BitConverter.GetBytes(int.Parse(str)));
        }


    }
}
